/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int root = 0;
        int in_left = 0;
        int in_right = inorder.length - 1;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return buildTree(preorder, root, in_left, in_right, map);
    }

    public TreeNode buildTree(int[] preorder, int root, int in_left, int in_right, Map<Integer, Integer> map) {
        if(in_left > in_right) {
            return null;
        }
        TreeNode rootNode = new TreeNode(preorder[root]);
        int i = map.get(preorder[root]);
        rootNode.left = buildTree(preorder, root + 1, in_left, i - 1, map);
        rootNode.right = buildTree(preorder, root + i - in_left + 1, i + 1, in_right, map);
        return rootNode;
    }
}